<template>
	<wd-form :model="model">
		<wd-cell-group border>
			<wd-input
				label="配送地址"
				label-width="100px"
				prop="address"
				clearable
				v-model="model.address"
				placeholder="请输入配送地址"
				:rules="[{ required: true, message: '请输入配送地址' }]"
			/>
		</wd-cell-group>
		<view class="btn">
			<view class="zhu">注：目前配送仅限鹤壁市淇滨区，其他地区暂不支持配送</view>
			<wd-button size="medium" type="error" @click="handleSubmit" block>提交</wd-button>
			<view class="zhu" @click="del(model.id)">删除地址</view>
		</view>
	</wd-form>
</template>

<script lang="ts" setup>
import { api } from '@/api/store_api';
import { get, toast, back, err } from '@/utils/uniapi';
import { reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
const model = reactive<{
	address: string;
	id: string;
	mchMemberNo: string;
}>({
	address: '',
	id: '',
	mchMemberNo: get('user').mchMemberNo
});
async function del(id: string) {
	try {
		wx.showModal({
			title: '提示',
			content: '您确定删除该地址吗？',
			complete: async (res: any) => {
				if (res.confirm) {
					const { respCode, msg } = await api.addressDel({ id });
					if (respCode === 200) {
						toast('删除成功');
						back();
					} else {
						toast(msg);
					}
				}
			}
		});
	} catch (e) {
		err(e);
	}
}
async function handleSubmit() {
	if (!model.address) return toast('请输入配送地址');
	if (model.id) {
		const res = await api.addressPut(model);
		console.log(res);
		if (res.respCode === 200) {
			toast('提交成功');
			back();
		}
	} else {
		const res = await api.addAddress(model);
		console.log(res);
		if (res.respCode === 200) {
			toast('提交成功');
			back();
		}
	}
}
async function getid(id: string) {
	try {
		const res = await api.addressGet({ id });
		if (res.respCode === 200) {
			const item = JSON.parse(res.source);
			console.log(item);
			model.address = item.address;
		}
	} catch (e) {
		err(e);
	}
}
onLoad((e) => {
	console.log(e);
	if (e.id) {
		const { id } = e;
		model.id = id;
		getid(id);
	}
});
</script>

<style lang="scss">
.btn {
	width: 690rpx;
	margin: 10rpx auto;
	position: fixed;
	bottom: 50rpx;
	left: 50%;
	transform: translateX(-50%);
	color: #666;
}
.zhu {
	text-align: center;
	font-size: 24rpx;
	margin: 10rpx 0;
}
</style>